package health.lm.com.component_base.popup.share;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import health.lm.com.component_base.R;
import health.lm.com.component_base.popup.model.PopupModel;
import health.lm.com.component_base.popup.uplevel.UpLevelBean;
import health.lm.com.component_base.popup.uplevel.UpLevelPopUtil;
import health.lm.com.component_base.widget.CustomPopWindow;
import health.lm.com.network.callback.SimpleCallBack;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

import static health.lm.com.component_base.helper.ImageLoaderHelper.IMG_ERROR;


/**
 * 分享弹出框
 */

public class SharePopUtil {
    private static final int SHARE_TYPE_NEWS = 1;
    private static final int SHARE_TYPE_POSTER = 2;
    private static final int SHARE_TYPE_CONTENT = 3;
    private static SharePopUtil sharePopUtil;
    private static Context ctx;
    private CustomPopWindow popWindow;
    private String url;
    private String title;
    private String description;
    private String avatar;
    private IWXAPI api;
    private View mRvHome;
    private int shareType = 0;
    private String newsId;
    private UMShareListener shareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            popWindow.dissmiss();
            if (shareType == SHARE_TYPE_POSTER) return;
            //ToastUtils.showShort("成功了");
            newsShareResult();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtils.showShort("分享失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtils.showShort("分享取消");
        }
    };
    private ImageView img;
    private View contentView;

    public static SharePopUtil getInstance() {
        if (sharePopUtil == null)
            sharePopUtil = new SharePopUtil();
        return sharePopUtil;
    }

    /**
     * 显示popwindow
     */
    public void show(Context context, View mLayoutPopup, String id) {
        this.shareType = SHARE_TYPE_NEWS;
        this.newsId = id;
        this.mRvHome = mLayoutPopup;
        ctx = context;
        this.contentView = LayoutInflater.from(context).inflate(R.layout.pop_share, null);
        //图片
        img = contentView.findViewById(R.id.iv_img);
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int heigth = dm.heightPixels;
        int width = dm.widthPixels;
        ViewGroup.LayoutParams lp = img.getLayoutParams();
        lp.width = width;
        lp.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        img.setLayoutParams(lp);
        img.setMaxWidth(width);
        img.setMaxHeight(heigth * 3);
        img.setMinimumHeight(heigth);

        //ImageLoaderHelper.getInstance().load(context, TestImgEntity.img1, img);
        //微信
        TextView wx = contentView.findViewById(R.id.tv_wx);
        wx.setOnClickListener(v -> {
            if (shareType == SHARE_TYPE_CONTENT) {
                shareContextType(SHARE_MEDIA.WEIXIN);
                return;
            }
            shareType(SHARE_MEDIA.WEIXIN);
        });
        //QQ
        TextView qq = contentView.findViewById(R.id.tv_qq);
        qq.setOnClickListener(v -> {
            if (shareType == SHARE_TYPE_CONTENT) {
                shareContextType(SHARE_MEDIA.QQ);
                return;
            }
            shareType(SHARE_MEDIA.QQ);
        });
        //朋友圈
        TextView pyq = contentView.findViewById(R.id.tv_pyq);
        pyq.setOnClickListener(v -> {
            if (shareType == SHARE_TYPE_CONTENT) {
                shareContextType(SHARE_MEDIA.WEIXIN_CIRCLE);
                return;
            }
            shareType(SHARE_MEDIA.WEIXIN_CIRCLE);
        });
        //取消
        TextView cancle = contentView.findViewById(R.id.tv_cancle);
        cancle.setOnClickListener(v -> popWindow.dissmiss());
        PopupModel.getInstance().shareImg(id, new SimpleCallBack<SharePopBean>() {
            @Override
            public void onSuccess(SharePopBean pSharePopBean) {
                url = pSharePopBean.getImg_url();
                Glide.with(context).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@android.support.annotation.NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int imageHeight = resource.getHeight();
                        RequestOptions options = new RequestOptions()
                                .placeholder(R.drawable.ic_image_loading)  //加载中显示的图片
                                //.centerCrop()            //图像则位于视图的中央
                                // .override(1090, 1090*3/4)
                                .dontAnimate()
                                .error(IMG_ERROR) //加载失败时显示的图片centerCrop().
                                .diskCacheStrategy(DiskCacheStrategy.ALL);  //图片缓存
                        if (imageHeight > 4096) {
                            imageHeight = 4096;
                            ViewGroup.LayoutParams layoutParams = img.getLayoutParams();
                            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                            layoutParams.height = imageHeight;
                            img.setLayoutParams(layoutParams);
                            //ImageLoaderHelper.getInstance().load(context, resource, img);
                            Glide.with(context).load(resource).apply(options).into(img);
                        } else {
                            Glide.with(context).load(resource).apply(options).into(img);
                        }
                    }
                });
                //创建并显示popWindow
                //显示大小
                showPop();
            }
        });
    }

    /**
     * 海报分享，获取海报接口不统一，新增方法
     *
     * @param context
     * @param mLayoutPopup
     * @param url
     */
    public void showPoster(Context context, View mLayoutPopup, String url) {
        this.shareType = SHARE_TYPE_POSTER;
        this.mRvHome = mLayoutPopup;
        this.url = url;
        ctx = context;
        this.contentView = LayoutInflater.from(context).inflate(R.layout.pop_share, null);
        //图片
        img = contentView.findViewById(R.id.iv_img);
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int heigth = dm.heightPixels;
        int width = dm.widthPixels;
        ViewGroup.LayoutParams lp = img.getLayoutParams();
        lp.width = width;
        lp.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        img.setLayoutParams(lp);
        img.setMaxWidth(width);
        img.setMaxHeight(heigth * 3);
        img.setMinimumHeight(heigth);

        //ImageLoaderHelper.getInstance().load(context, TestImgEntity.img1, img);
        //微信
        TextView wx = contentView.findViewById(R.id.tv_wx);
        wx.setOnClickListener(v -> {
            if (shareType == SHARE_TYPE_CONTENT) {
                shareContextType(SHARE_MEDIA.WEIXIN);
                return;
            }
            shareType(SHARE_MEDIA.WEIXIN);
        });
        //QQ
        TextView qq = contentView.findViewById(R.id.tv_qq);
        qq.setOnClickListener(v -> {
            if (shareType == SHARE_TYPE_CONTENT) {
                shareContextType(SHARE_MEDIA.QQ);
                return;
            }
            shareType(SHARE_MEDIA.QQ);
        });
        //朋友圈
        TextView pyq = contentView.findViewById(R.id.tv_pyq);
        pyq.setOnClickListener(v -> {
            if (shareType == SHARE_TYPE_CONTENT) {
                shareContextType(SHARE_MEDIA.WEIXIN_CIRCLE);
                return;
            }
            shareType(SHARE_MEDIA.WEIXIN_CIRCLE);
        });
        //取消
        TextView cancle = contentView.findViewById(R.id.tv_cancle);
        cancle.setOnClickListener(v -> popWindow.dissmiss());

        Glide.with(context).asBitmap().load(this.url).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@android.support.annotation.NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                int imageHeight = resource.getHeight();
                RequestOptions options = new RequestOptions()
                        .placeholder(R.drawable.ic_image_loading)  //加载中显示的图片
                        //.centerCrop()            //图像则位于视图的中央
                        // .override(1090, 1090*3/4)
                        .dontAnimate()
                        .error(IMG_ERROR) //加载失败时显示的图片centerCrop().
                        .diskCacheStrategy(DiskCacheStrategy.ALL);  //图片缓存
                if (imageHeight > 4096) {
                    imageHeight = 4096;
                    ViewGroup.LayoutParams layoutParams = img.getLayoutParams();
                    layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                    layoutParams.height = imageHeight;
                    img.setLayoutParams(layoutParams);
                    //ImageLoaderHelper.getInstance().load(context, resource, img);
                    Glide.with(context).load(resource).apply(options).into(img);
                } else {
                    Glide.with(context).load(resource).apply(options).into(img);
                }
            }
        });
        //创建并显示popWindow
        //显示大小
        showPop();
    }

    /**
     * 文本分享，一般默认的分享样式
     *
     * @param context      context
     * @param mLayoutPopup mLayoutPopup
     * @Param json         分享内容id
     */
    public void showContent(Context context, View mLayoutPopup, String pTitle,String pDesc,String pImage,String pUrl) {
//        if (TextUtils.isEmpty(json)) return;
        this.shareType = SHARE_TYPE_CONTENT;
        this.mRvHome = mLayoutPopup;
        ctx = context;
        avatar = pImage;
        url = pUrl;
        title = pTitle;
        description = pDesc;
        this.contentView = LayoutInflater.from(context).inflate(R.layout.pop_share, null);

        contentView.findViewById(R.id.share_tv_top).setVisibility(View.INVISIBLE);
        ImageView img = contentView.findViewById(R.id.iv_img);
        img.setVisibility(View.GONE);
        //微信
        TextView wx = contentView.findViewById(R.id.tv_wx);
        wx.setOnClickListener(v -> shareContextType(SHARE_MEDIA.WEIXIN));
        //QQ
        TextView qq = contentView.findViewById(R.id.tv_qq);
        qq.setOnClickListener(v -> shareContextType(SHARE_MEDIA.QQ));
        //朋友圈
        TextView pyq = contentView.findViewById(R.id.tv_pyq);
        pyq.setOnClickListener(v -> shareContextType(SHARE_MEDIA.WEIXIN_CIRCLE));
        //取消
        TextView cancle = contentView.findViewById(R.id.tv_cancle);
        cancle.setOnClickListener(v -> popWindow.dissmiss());
        //创建并显示popWindow
        showPop();
        //PopupModel.getInstance().textShare(id, new SimpleCallBack<ShareTextBean>() {
        //    @Override
        //    public void onSuccess(ShareTextBean pShareTextBean) {
        //        avatar = pShareTextBean.getLink_img();
        //        url = pShareTextBean.getLink_url();
        //        title = pShareTextBean.getLink_title();
        //        description = pShareTextBean.getLink_desc();
        //    }
        //});
    }

    /**
     * 文本分享，一般默认的分享样式
     * @param context
     * @param mLayoutPopup
     * @param type 1资讯 2商品 3邀请好友
     * @param id  资讯id 商品id 邀请好友可以为空
     */
    public final static String TYPE_INFORMATION = "1";
    public final static String TYPE_GOODS = "2";
    public final static String TYPE_INIVTE_FRIEND = "3";
    public void shareUrl(Context context, View mLayoutPopup,String type,String id) {
        this.shareType = SHARE_TYPE_CONTENT;
        this.mRvHome = mLayoutPopup;
        ctx = context;
        contentView.findViewById(R.id.share_tv_top).setVisibility(View.INVISIBLE);
        this.contentView = LayoutInflater.from(context).inflate(R.layout.pop_share, null);
        ImageView img = contentView.findViewById(R.id.iv_img);
        img.setVisibility(View.GONE);
        //微信
        TextView wx = contentView.findViewById(R.id.tv_wx);
        wx.setOnClickListener(v -> shareContextType(SHARE_MEDIA.WEIXIN));
        //QQ
        TextView qq = contentView.findViewById(R.id.tv_qq);
        qq.setOnClickListener(v -> shareContextType(SHARE_MEDIA.QQ));
        //朋友圈
        TextView pyq = contentView.findViewById(R.id.tv_pyq);
        pyq.setOnClickListener(v -> shareContextType(SHARE_MEDIA.WEIXIN_CIRCLE));
        //取消
        TextView cancle = contentView.findViewById(R.id.tv_cancle);
        cancle.setOnClickListener(v -> popWindow.dissmiss());
        PopupModel.getInstance().textShare(type, id, new SimpleCallBack<ShareTextBean>() {
            @Override
            public void onSuccess(ShareTextBean shareTextBean) {
                avatar = shareTextBean.getLink_img();
                url = shareTextBean.getLink_url();
                title = shareTextBean.getLink_title();
                description = shareTextBean.getLink_desc();
                //创建并显示popWindow
                showPop();
            }
        });

    }
    private void showPop() {
        popWindow = new CustomPopWindow.PopupWindowBuilder(ctx)
                .setView(contentView)
                .enableBackgroundDark(true)
                .setBgDarkAlpha(0.7f)
                .setAnimationStyle(R.style.pop_bottom_anim)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
                .create()
                .showAtLocation(mRvHome, Gravity.BOTTOM, 0, 0);
    }

    private void newsShareResult() {
        if (null == newsId || newsId.equals("")) {
            return;
        }
        PopupModel.getInstance().NewsShareResult(newsId, new SimpleCallBack<UpLevelBean>() {
            @Override
            public void onSuccess(UpLevelBean pUpLevelBean) {
                //判断是否升级 弹窗
                UpLevelPopUtil.getInstance().init(ctx, mRvHome);
                //分享获得糖果通知弹窗
                if (pUpLevelBean.getStatus().equals("0")) {
                    return;
                }
                NoticePopUtil.getInstance().showShare(ctx, mRvHome, pUpLevelBean);
            }
        });
    }

//    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.tv_wx://微信
//                if (shareType == SHARE_TYPE_CONTENT) {
//                    shareContextType(SHARE_MEDIA.WEIXIN);
//                    return;
//                }
//                shareType(SHARE_MEDIA.WEIXIN);
////                RxView.clicks(v).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
////                    if (shareType == SHARE_TYPE_CONTENT) {
////                        shareContextType(SHARE_MEDIA.WEIXIN);
////                        return;
////                    }
////                    shareType(SHARE_MEDIA.WEIXIN);
////                });
//                break;
//            case R.id.tv_qq://qq
//                if (shareType == SHARE_TYPE_CONTENT) {
//                    shareContextType(SHARE_MEDIA.QQ);
//                    return;
//                }
//                shareType(SHARE_MEDIA.QQ);
////                RxView.clicks(v).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
////                    if (shareType == SHARE_TYPE_CONTENT) {
////                        shareContextType(SHARE_MEDIA.QQ);
////                        return;
////                    }
////                    shareType(SHARE_MEDIA.QQ);
////                });
//                break;
//            case R.id.tv_pyq://朋友圈
//                if (shareType == SHARE_TYPE_CONTENT) {
//                    shareContextType(SHARE_MEDIA.WEIXIN_CIRCLE);
//                    return;
//                }
//                shareType(SHARE_MEDIA.WEIXIN_CIRCLE);
////                RxView.clicks(v).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
////                    if (shareType == SHARE_TYPE_CONTENT) {
////                        shareContextType(SHARE_MEDIA.WEIXIN_CIRCLE);
////                        return;
////                    }
////                    shareType(SHARE_MEDIA.WEIXIN_CIRCLE);
////                });
//                break;
//            case R.id.tv_cancle://取消
//                popWindow.dissmiss();
//                break;
//        }
//        //此处目的：https://developer.umeng.com/docs/66632/detail/66948?um_channel=sdk
//        //重复调用了onPause 、onResume，以此判断
//        if (/*shareType == SHARE_TYPE_POSTER && */null != popWindow) popWindow.dissmiss();
//    }

    private void shareType(SHARE_MEDIA type) {
        new RxPermissions((Activity) ctx).requestEachCombined(Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer<Permission>() {
            @Override
            public void accept(@NonNull Permission permission) throws Exception {
                if (permission.granted) {
                    UMImage imageurl = new UMImage(ctx, url);
                    imageurl.setThumb(new UMImage(ctx, R.mipmap.ic_launcher));
                    new ShareAction(((Activity) ctx)).withMedia(imageurl)
                            .setPlatform(type)
                            .setCallback(shareListener).share();
                } else if (permission.shouldShowRequestPermissionRationale) {
                    //拒绝权限请求
                    ToastUtils.showShort("请开启相机和读写手机存储权限");
                } else {
                    // 拒绝权限请求,并不再询问
                    // 可以提醒用户进入设置界面去设置权限
                    ToastUtils.showShort("已拒绝相机和读写手机存储权限，请到设置页面开启权限");
                }
            }
        });
    }

    /**
     * 纯文本分享
     *
     * @param type type
     */
    private void shareContextType(SHARE_MEDIA type) {
        new RxPermissions((Activity) ctx).requestEachCombined(Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer<Permission>() {
            @Override
            public void accept(@NonNull Permission permission) throws Exception {
                if (permission.granted) {
                    UMImage imageurl = new UMImage(ctx, avatar);
                    UMWeb web = new UMWeb(url);
                    web.setTitle(title);//标题
                    web.setThumb(imageurl);  //缩略图
                    web.setDescription(description);//描述
                    new ShareAction(((Activity) ctx)).withMedia(web)
                            .setPlatform(type)
                            .setCallback(shareListener).share();
                } else if (permission.shouldShowRequestPermissionRationale) {
                    //拒绝权限请求
                    ToastUtils.showShort("请开启相机和读写手机存储权限");
                } else {
                    // 拒绝权限请求,并不再询问
                    // 可以提醒用户进入设置界面去设置权限
                    ToastUtils.showShort("已拒绝相机和读写手机存储权限，请到设置页面开启权限");
                }
            }
        });
    }
}
